<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Encrypt extends Command
{
    /**
     * 控制台调用操作
     *
     * @var string
     */
    protected $signature = 'encrypt:encryption 
                            {info?} {key?}
                            {--he|help :帮助信息}';

    /**
     * 命令描述信息.
     *
     * @var string
     */
    protected $description = '对数据库信息或其他信息进行加密';

    /**
     * 创建一个命令实例
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 命令执行操作
     *
     * @return mixed
     */
    public function handle()
    {
        $info = $this->argument('info');
        $key = $this->argument('key');
        if ($info) {
//            $key = password_hash($info, PASSWORD_BCRYPT);
            $key = empty($key) ? password_hash($info, PASSWORD_BCRYPT) : $key;
            $this->table(['text', 'pass', 'key'], [array($info, encrypt_func($info, $key), $key)]);
            return;
        }

        if (!$this->confirm('确定生成密码及秘钥吗?[y|n]')) {
            $this->error("已取消");
            return;
        }
        //进度条
        $this->info('进度条');
        $this->output->progressStart(3);
        for ($i = 0; $i < 3; $i++) {
            $this->output->progressAdvance();
        }
        $this->output->progressFinish();
        //生成键值
        $D_KEY = password_hash(env('DB_DATABASE'), PASSWORD_BCRYPT);
        $DB_DATABASE = encrypt_func(env('DB_DATABASE'), env($D_KEY));

        $U_KEY = password_hash(env('DB_USERNAME'), PASSWORD_BCRYPT);
        $DB_USERNAME = encrypt_func(env('DB_USERNAME'), env($U_KEY));
        $P_KEY = password_hash(env('DB_PASSWORD'), PASSWORD_BCRYPT);
        $DB_PASSWORD = encrypt_func(env('DB_PASSWORD'), env($P_KEY));

        $headers = ['name', 'oldData', 'addKey', 'addKeyVal', 'encrypt'];
        $array = [
            array('DB_DATABASE', env('DB_DATABASE'), 'DATABASE_KEY', $D_KEY, $DB_DATABASE),
            array('DB_USERNAME', env('DB_USERNAME'), 'USER_KEY', $U_KEY, $DB_USERNAME),
            array('DB_PASSWORD', env('DB_PASSWORD'), 'PASSWORD_KEY', $P_KEY, $DB_PASSWORD),

        ];
        $this->table($headers, $array);
        $this->info('创建成功!');
    }
}
